
(function() {
owd <- getwd()
on.exit({setwd(owd)})


ROOT <- rprojroot::find_package_root_file()
ACE_VERSION <- "1.4.14"
ACE_FILES <- c(
  "ace.js",
  "ext-language_tools.js",
  "mode-css.js",
  "mode-html.js",
  "mode-javascript.js",
  "mode-plain_text.js",
  "mode-r.js",
  "mode-rdoc.js",
  "mode-rhtml.js",
  "mode-text.js",
  "mode-xml.js"
)
ACE_THEME_PREFIX <- "theme-"

url <- sprintf(
  "https://github.com/ajaxorg/ace-builds/archive/v%s.tar.gz",
  ACE_VERSION
)

destfile <- tempfile("ace-tarball-")
on.exit({unlink(destfile)}, add = TRUE)
download.file(url, destfile = destfile)


exdir <- tempfile("ace-")
on.exit({unlink(exdir, recursive = TRUE)}, add = TRUE)
dir.create(exdir)
untar(tarfile = destfile, exdir = exdir)

setwd(exdir)
setwd(sprintf("ace-builds-%s", ACE_VERSION))


source <- c(
  file.path("src-min", ACE_FILES),
  dir("src-min", pattern = ACE_THEME_PREFIX, full.names = TRUE)
)
contents <- paste(lapply(source, function(file) {
  readChar(file, file.info(file)$size, TRUE)
}), collapse = "\n")

target <- file.path(ROOT, "inst/lib/ace/ace.js")
writeLines(contents, con = target, sep = "\n", useBytes = TRUE)

themes <- sub("^theme-", "", sub("\\.js$", "", dir("src", "^theme-")))

metadata <- c(
  "# This file was autogenerated by 'tools/update-ace.R'",
  paste0("ACE_VERSION <- ", shQuote(ACE_VERSION, "cmd")),
  paste0("ACE_THEMES <- c(", paste0(shQuote(themes, "cmd"), collapse = ", "), ")")
)

cat("Saving metadata:\n\n", paste0(metadata, collapse = '\n'), "\n")
writeLines(metadata, con = file.path(ROOT, "R/ace.R"))
})()
